import { create } from 'zustand';
import type { BannerModel } from '../models/bannerModel';
import { addBannerList, editBannerListApi, getBannerList } from '../apis/bannerApi';

interface bannerState {
  bannerList: BannerModel[]; // 原始完整数据
  paginatedBannerList: BannerModel[]; // 分页后的数据
  getBannerList: () => Promise<void>;
  addBannerList: (obj: BannerModel) => Promise<void>;
  editBannerList: (obj: BannerModel) => Promise<void>;
  // 分页相关状态
  currentPage: number;
  pageSize: number;
  total: number;
  // 分页方法
  setPageSize: (size: number) => void;
  setCurrentPage: (page: number) => void;
  // 前端分页处理
  handlePagination: () => void;
}

export const useBannerStore = create<bannerState>()((set, get) => ({
  bannerList: [],
  paginatedBannerList: [],
  currentPage: 1,
  pageSize: 5,
  total: 0,
  
  getBannerList: async () => {
    const res = await getBannerList();
    set({ 
      bannerList: res.data, 
      total: res.data.length,
      currentPage: 1 // 重置到第一页
    });
    // 立即执行分页
    get().handlePagination();
  },
  
  addBannerList: async (obj) => {
    await addBannerList(obj);
  },

  editBannerList: async (obj) => {
    const res = await editBannerListApi(obj);
    console.log(res);
  },
  
  setPageSize: (size) => {
    set({ pageSize: size, currentPage: 1 }); // 更改页大小时重置到第一页
    get().handlePagination();
  },
  
  setCurrentPage: (page) => {
    set({ currentPage: page });
    get().handlePagination();
  },
  
  handlePagination: () => {
    const { bannerList, currentPage, pageSize } = get();
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = bannerList.slice(startIndex, endIndex);
    set({ paginatedBannerList: paginatedData });
  }
}));
